package fm.dongman.modellib.source;

import org.jetbrains.annotations.NotNull;

import fm.dongman.animefm.contractlib.BaseDataSource;
import fm.dongman.animefm.contractlib.contract.FSheetContract;
import fm.dongman.animefm.contractlib.model.FSheetDataModel;
import fm.dongman.modellib.local.FSheetLocalDataSource;
import fm.dongman.modellib.remote.FSheetRemoteDataSource;

/**
 * 漫单
 * Created by KUIGE on 2017/10/14.
 */

public class FSheetRepository implements FSheetContract.IFSheetDataSource {
    //单例对象
    private static FSheetRepository SINGLETON;
    //网络加载
    private FSheetRemoteDataSource mFSheetRemoteDataSource;
    //本地加载
    private FSheetLocalDataSource mFSheetLocalDataSource;

    private FSheetRepository(FSheetRemoteDataSource instance, FSheetLocalDataSource fSheetLocalDataSource) {
        mFSheetRemoteDataSource = instance;
        mFSheetLocalDataSource = fSheetLocalDataSource;
    }

    /**
     * 返回单例对象
     */
    public static FSheetRepository getInstance(FSheetRemoteDataSource instance, FSheetLocalDataSource fSheetLocalDataSource) {
        if (SINGLETON == null) {
            SINGLETON = new FSheetRepository(instance, fSheetLocalDataSource);
        }
        return SINGLETON;
    }

    @Override
    public void getData(@NotNull final LoadSourceCallback<? super FSheetDataModel> callback) {
        //先加载网络数据
        mFSheetRemoteDataSource.getData(new LoadSourceCallback<FSheetDataModel>() {
            @Override
            public void onDataLoaded(FSheetDataModel dataModel) {
                callback.onDataLoaded(dataModel);
            }

            @Override
            public void onDataLoadFiled() {
                loadLocalData(callback);

            }
        });
    }

    /**
     * 本地数据获取
     * @param callback 回调
     */
    private void loadLocalData( final LoadSourceCallback<? super FSheetDataModel> callback) {
        //加载失败时加载本地数据
        mFSheetLocalDataSource.getData(new LoadSourceCallback<FSheetDataModel>() {
            @Override
            public void onDataLoaded(FSheetDataModel dataModel) {
                callback.onDataLoaded(dataModel);
            }

            @Override
            public void onDataLoadFiled() {
                callback.onDataLoadFiled();
            }
        });
    }

    @Override
    public void saveData(FSheetDataModel dataModel) {
        mFSheetLocalDataSource.saveData(dataModel);
    }

    @Override
    public void refreshData() {
    }

    @Override
    public void offLine() {
        mFSheetRemoteDataSource.offLine();
    }
}
